/*
 * Copyright (c)  2015~2020, xforceplus
 * All rights reserved.
 * Project:datacare-orm
 * Id: RowMapperResultSetExt.java   2020-10-10 14-20-41
 * Author: Evan
 */
package cn.datacare.orm.mapping;

import cn.datacare.orm.damoin.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: 2015~2020
 * </p>
 * <p>
 * Company/Department: xforceplus
 * </p>
 *
 * @author Evan
 * <b>Creation Time:</b> 2020-10-10 14-20-41
 * @since V1.0
 */
public class RowMapperResultSetExt<T> implements ResultSetExt<List<T>> {

    BeanProcessor beanProcessor = null;
    private RowMapper<T> rowMapper;

    public RowMapperResultSetExt(RowMapper<T> _rowMapper, BeanProcessor beanProcessor) {
        this.rowMapper = _rowMapper;
        this.beanProcessor = beanProcessor;
    }

    @Override
    public List<T> handleResultSet(String sqlId, ResultSet rs, Class<?> z) throws SQLException {
        int rowNum = 0;
        List<T> resultList = new ArrayList<T>();
        if (Map.class.isAssignableFrom(z)) {
            while (rs.next()) {
                Object obj = beanProcessor.toMap(sqlId, z, rs);
                resultList.add(this.rowMapper.mapRow(obj, rs, rowNum++));
            }
        }
        while (rs.next()) {
            Object obj = beanProcessor.toBean(rs, z);
            resultList.add(this.rowMapper.mapRow(obj, rs, rowNum++));
        }
        return resultList;
    }
}
